package com.toefl.speaking.helper;

import java.io.File;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.toefl.speaking.R;
import com.toefl.speaking.activity.QuestionActivity;
import com.toefl.speaking.business.QuestionUserBusiness;
import com.toefl.speaking.dao.bean.QuestionUserBean;
import com.toefl.speaking.handler.QuestionHandler;
import com.toefl.speaking.handler.RewardHandler;
import com.toefl.speaking.handler.RewardHandler.Reward;
import com.toefl.speaking.util.AppConstans;

public class CustomDialog extends AlertDialog implements android.view.View.OnClickListener {

	private Context context;
	private AlertType type = AlertType.DIALOG_ALERT;

	private String message;

	private Button btn_close, btn_play, btn_re_recording, btn_save, btn_upload, btn_reward;
	private MediaPlayer mediaPlayer;
	private TextView tv;

	public CustomDialog(Context context, AlertType alertType) {
		super(context);
		this.context = context;
		type = alertType;
	}

	public CustomDialog(Context context, int theme, AlertType alertType) {
		super(context, theme);
		type = alertType;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dialog_alert);
		btn_close = (Button) findViewById(R.id.btn_close);
		btn_play = (Button) findViewById(R.id.btn_play);
		btn_re_recording = (Button) findViewById(R.id.btn_re_recording);
		btn_save = (Button) findViewById(R.id.btn_save);
		btn_upload = (Button) findViewById(R.id.btn_upload);
		btn_reward = (Button) findViewById(R.id.btn_reward);
		switch (type) {

		case DIALOG_ALERT:

			tv = (TextView) findViewById(R.id.msg);
			tv.setText(message);
			btn_close.setOnClickListener(this);
			btn_play.setOnClickListener(this);
			btn_re_recording.setOnClickListener(this);
			btn_save.setOnClickListener(this);
			btn_upload.setOnClickListener(this);
			btn_reward.setOnClickListener(this);
			break;

		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_close:
			dismiss();
			break;
		case R.id.btn_play:
			playVideo();
			break;
		case R.id.btn_re_recording:
			dismiss();
			break;
		case R.id.btn_save:
			tv.setText(String.valueOf(saveAduio()));
			if (QuestionUserBusiness.getQuestionInfoByQID(String.valueOf(QuestionActivity.questionID), "111") != null) {

				// 更新数据库 录音路径
			} else {
				// 直接插入数据库
				QuestionUserBean qustionUser = new QuestionUserBean();
				qustionUser.question_id = QuestionActivity.questionID;
				qustionUser.uesr_id = 111;
				qustionUser.question_user_audio_path = Environment.getExternalStorageDirectory().getAbsolutePath()
						+ AppConstans.PROJECT_PATH + AppConstans.RECORD_AUDIO + "/" + 111 + "_"
						+ qustionUser.question_id + ".mp3";
				QuestionUserBusiness.saveAudio(qustionUser);
			}
			// QuestionBusiness questionBusiness = new QuestionBusiness();
			// if (questionBusiness.isExistQuestionBean(String.valueOf(QuestionActivity.questionBean.question_id))) {
			//
			// }
			// boolean a = questionBusiness.saveUpdateCustomer(QuestionActivity.questionBean);
			// tv.setText(a ? "db保存成功" : "db保存失败");
			break;
		case R.id.btn_upload:
			postRecordUpload(QuestionActivity.questionID);
			break;
		case R.id.btn_reward:
			postReward();
			break;

		}

	}

	public void setMessage(String msg) {
		message = msg;
	}

	public static enum AlertType {
		DIALOG_WAITING,
		DIALOG_ALERT
	}

	/**
	 * 设置对话框相关属性
	 */
	public void setProperty() {
		Window window = this.getWindow(); // 得到对话框的窗口．
		WindowManager.LayoutParams wl = window.getAttributes();
		wl.x = 0; // 这两句设置了对话框的位置．0为中间
		wl.y = 51;
		// wl.alpha=0.6f;//这句设置了对话框的透明度
		wl.gravity = Gravity.BOTTOM;
		window.setAttributes(wl);
	}

	/**
	 * 播放录音
	 */
	public void playVideo() {
		String path = Environment.getExternalStorageDirectory() + File.separator + "test.mp3";
		mediaPlayer = new MediaPlayer();
		try {
			mediaPlayer.setDataSource(context, Uri.parse("file://" + path));
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 保存文件
	 * @return
	 */
	private boolean saveAduio() {
		File tempFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test.mp3");
		if (!new File(Environment.getExternalStorageDirectory().getAbsolutePath() + AppConstans.PROJECT_PATH
				+ AppConstans.RECORD_AUDIO).exists()) {
			File temp = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + AppConstans.PROJECT_PATH
					+ AppConstans.RECORD_AUDIO);
			temp.mkdirs();
		}
		File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + AppConstans.PROJECT_PATH
				+ AppConstans.RECORD_AUDIO);
		File file = new File(dir, "userId" + "_" + "questionID" + ".mp3");
		return tempFile.renameTo(file);

	}

	/**
	 * 请求上传录音 批改
	 * @param questionId
	 */
	private void postRecordUpload(int questionId) {
		QuestionHandler questionHandler = QuestionHandler.instance();
		String result = null;
		File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + AppConstans.PROJECT_PATH
				+ AppConstans.RECORD_AUDIO);
		File file = new File(dir, "userId" + "_" + "questionID" + ".mp3");
		try {
			result = questionHandler.postQuestionCorrect(questionId, file);
			JSONObject jsonResult = new JSONObject(result).getJSONObject("Quid");
		} catch (Exception e) {

		}
	}

	private void postReward() {

		RewardHandler rewardHandler = RewardHandler.instance();
		Reward reward = rewardHandler.getRewardIssue();
		reward.setAmount("20");
		reward.setLifeTime("15");
		String result = null;
		try {
			result = rewardHandler.postRewardIssue(reward, QuestionActivity.questionID);
			JSONObject jsonResult = new JSONObject(result).getJSONObject("Quid");
		} catch (Exception e) {

		}

	}
}
